<template>
  <view class="container">
    <!-- 收货地址 -->
    <view class="address-section" @tap="selectAddress">
      <view class="address-box" v-if="selectedAddress">
        <view class="info">
          <view class="user">
            <text class="name">{{ selectedAddress.receiverName }}</text>
            <text class="phone">{{ selectedAddress.phoneNumber }}</text>
          </view>
          <view class="address">
            {{
              `${selectedAddress.province}${selectedAddress.city}${selectedAddress.district}${selectedAddress.detailAddress}`
            }}
          </view>
        </view>
        <uni-icons type="right" size="20" color="#999"></uni-icons>
      </view>
      <view class="no-address" v-else>
        <text>请选择收货地址</text>
        <uni-icons type="right" size="20" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-section">
      <view class="goods-item" v-for="item in orderGoods" :key="item.skuId">
        <image :src="item.primaryImage" mode="aspectFill" class="goods-image" />
        <view class="goods-info">
          <text class="goods-name">{{ item.title }}</text>
          <text class="goods-specs">{{ item.specs }}</text>
          <view class="price-box">
            <text class="price">¥{{ item.salePrice }}</text>
            <text class="count">x{{ item.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-section">
      <view class="item">
        <text>商品总价</text>
        <text class="price">¥{{ totalPrice }}</text>
      </view>
      <view class="item">
        <text>运费</text>
        <text class="price">¥{{ freight }}</text>
      </view>
      <view class="item">
        <text>优惠券</text>
        <view class="coupon" @tap="selectCoupon">
          <text>{{
            selectedCoupon ? `省${selectedCoupon.amount}元` : "未使用"
          }}</text>
          <uni-icons type="right" size="20" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 备注 -->
    <view class="remark-section">
      <text class="label">备注</text>
      <input
        type="text"
        v-model="remark"
        placeholder="选填：请填写备注信息"
        class="remark-input"
      />
    </view>

    <!-- 底部结算 -->
    <view class="footer">
      <view class="total">
        合计：<text class="price">¥{{ actualPrice }}</text>
      </view>
      <button class="submit-btn" @tap="submitOrder">提交订单</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useCartStore } from "@/store/cartStore";
import { userService } from "@/services/user";
import { orderService } from "@/services/order";
import { goodsService } from "@/services/goods";

// 响应式数据
const selectedAddress = ref(null);
const orderGoods = ref([]);
const selectedCoupon = ref(null);
const remark = ref("");
const freight = ref(0);

// 计算商品总价
const totalPrice = computed(() => {
  return orderGoods.value.reduce((total, item) => {
    return total + item.salePrice * item.quantity;
  }, 0);
});

// 计算实际支付价格
const actualPrice = computed(() => {
  let price = totalPrice.value + freight.value;
  if (selectedCoupon.value) {
    price -= selectedCoupon.value.amount;
  }
  return price;
});

// 选择收货地址
const selectAddress = () => {
  uni.navigateTo({
    url: "/pages/address/list?select=1",
  });
};

// 选择优惠券
const selectCoupon = () => {
  uni.navigateTo({
    url: `/pages/coupon/list?select=1&amount=${totalPrice.value}`,
  });
};

// 提交订单
const submitOrder = async () => {
  try {
    // 验证收货地址
    if (!selectedAddress.value) {
      uni.showToast({
        title: "请选择收货地址",
        icon: "none",
      });
      return;
    }

    // 构建订单数据
    const orderData = {
      addressId: selectedAddress.value.id,
      items: orderGoods.value.map((item) => ({
        spuId: item.spuId,
        skuId: item.skuId,
        quantity: item.quantity,
        title: item.title,
        salePrice: item.salePrice,
        specs: item.specs,
        linePrice: item.linePrice,
        code: item.code,
        unit: item.unit,
      })),
      couponId: selectedCoupon.value?.id,
      remark: remark.value,
    };

    // 创建订单
    const res = await orderService.createOrder(orderData);

    if (res.success) {
      // 创建订单成功后跳转到支付页面
      uni.redirectTo({
        url: `/pages/order/pay?orderId=${res.data.id}&amount=${res.data.payAmount}`,
      });
    }
  } catch (error) {
    console.error("提交订单失败:", error);
    uni.showToast({
      title: error.message || "提交订单失败",
      icon: "none",
    });
  }
};

// 页面加载
onLoad(async (options) => {
  const { skuId, quantity } = options;

  if (skuId) {
    // 直接购买
    const res = await goodsService.getGoodsDetail(skuId);
    if (res.success) {
      orderGoods.value = [
        {
          ...res.data,
          quantity: parseInt(quantity),
        },
      ];
    }
  } else {
    // 购物车结算
    const cartStore = useCartStore();
    orderGoods.value = cartStore.getSelectedGoods();
  }
});

// 获取默认地址
async function loadDefaultAddress() {
  try {
    const res = await userService.getDefaultAddress();
    console.log("获取默认地址响应:", res);

    if (res.success && res.data) {
      selectedAddress.value = res.data;
    } else {
      // 如果没有默认地址，尝试获取地址列表的第一个
      const listRes = await userService.getAddressList();
      if (listRes.success && listRes.data && listRes.data.length > 0) {
        selectedAddress.value = listRes.data[0];
      }
    }
  } catch (error) {
    console.error("获取默认地址失败:", error);
    uni.showToast({
      title: "获取地址信息失败",
      icon: "none",
    });
  }
}

// 页面加载时获取默认地址
onMounted(async () => {
  await loadDefaultAddress();
});

// 需要添加一个更新地址的方法，供地址选择页面回调使用
const updateAddress = (address) => {
  selectedAddress.value = address;
};

// 确保 updateAddress 方法被导出
defineExpose({
  updateAddress,
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.address-section {
  background-color: #fff;
  margin-bottom: 20rpx;

  .address-box {
    display: flex;
    align-items: center;
    padding: 30rpx;

    .info {
      flex: 1;

      .user {
        margin-bottom: 10rpx;

        .name {
          font-size: 30rpx;
          margin-right: 20rpx;
        }

        .phone {
          font-size: 28rpx;
          color: #666;
        }
      }

      .address {
        font-size: 26rpx;
        color: #333;
        line-height: 1.4;
      }
    }
  }

  .no-address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.goods-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;

  .goods-item {
    display: flex;
    padding: 20rpx 0;

    .goods-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
    }

    .goods-info {
      flex: 1;
      margin-left: 20rpx;

      .goods-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }

      .goods-specs {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
      }

      .price-box {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .price {
          font-size: 32rpx;
          color: #ff4444;
          font-weight: bold;
        }

        .count {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
  }
}

.order-section {
  background-color: #fff;
  margin-bottom: 20rpx;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    font-size: 28rpx;

    .price {
      color: #ff4444;
    }

    .coupon {
      display: flex;
      align-items: center;
      color: #666;

      text {
        margin-right: 10rpx;
      }
    }
  }
}

.remark-section {
  background-color: #fff;
  padding: 30rpx;
  display: flex;
  align-items: center;

  .label {
    font-size: 28rpx;
    margin-right: 20rpx;
  }

  .remark-input {
    flex: 1;
    font-size: 28rpx;
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;

  .total {
    flex: 1;
    font-size: 28rpx;

    .price {
      font-size: 36rpx;
      color: #ff4444;
      font-weight: bold;
    }
  }

  .submit-btn {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #ff4444;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;
  }
}
</style>
